/**
 * Filename: AlbumStatusFragment.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 14:43
 */
package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.AlbumStatusAdapter;
import com.github.postsanf.yinian.adapter.CardAlbumStatusAdapter;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import jp.wasabeef.recyclerview.animators.ScaleInAnimator;

public class AlbumStatusFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private View view;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshlayout;
    private AlbumStatusAdapter mAlbumStatusAdapter;
    private CardAlbumStatusAdapter mCardAlbumStatusAdapter;
    private List<YNStatus> groupStatusItems = new ArrayList<>();
    private boolean isBottom;
    private boolean isOfficialAlbum;
    private boolean isFromHome = false;
    private Handler handler = new Handler();
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    private boolean refresh = false;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        registerBroadcastReceiver();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit();
            }
        }, 200);
        try {
            if (getActivity().getIntent() != null) {
                isFromHome = getActivity().getIntent().getBooleanExtra(ACTIONs.aAddData, false);
            }
        } catch (NullPointerException e) {
            isFromHome = false;
        }
        isOfficialAlbum = TextUtils.equals((YNSingleton.getInstance().getCurAlbum().getGtype()), getString(R.string.gfxc));
        initView();
        return view;
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_include_album_status, null);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.album_status_recyclerview);
        mRefreshlayout = (SwipeRefreshLayout) view.findViewById(R.id.album_status_swipe_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setOnRefreshListener(this);
        mRefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        // 初始加载刷新
        mRefreshlayout.setRefreshing(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mRecyclerView.setItemAnimator(new ScaleInAnimator(new OvershootInterpolator(1f)));
        if (isOfficialAlbum) {
            mAlbumStatusAdapter = new AlbumStatusAdapter(getActivity(), groupStatusItems, isOfficialAlbum ? 1 : 0);
            mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAlbumStatusAdapter);
            mRecyclerView.setAdapter(mYNRecyclerViewAdapter);
        } else {
            mCardAlbumStatusAdapter = new CardAlbumStatusAdapter(getActivity(), groupStatusItems, isOfficialAlbum ? 1 : 0, application.getCurID(), application.getCurGid());
            mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mCardAlbumStatusAdapter);
            mRecyclerView.setAdapter(mYNRecyclerViewAdapter);
        }
        // 主页进入则默认已加入相册中
        if (isFromHome || (isOfficialAlbum && YNSingleton.getInstance().getCurAlbum().getIsInAlbum() == 1)) {
            if (isOfficialAlbum) {
                mAlbumStatusAdapter.setIsInAlbum(true);
            }
        }
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//              ((AlbumStatusActivity) getActivity()).showActionButton(dy < 1);
            }
        });
        mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }
                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.Loading, null);
                mRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isOfficialAlbum) {
                            loadOfficialStatus(false, CommonConstants.YNS_SIGN_LOAD);
                        } else {
                            loadStatus(false, ACTIONs.actionAlbumStatus);
                        }
                    }
                }, 500);
            }
        });
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 通知后台刷新页面
                if (isOfficialAlbum) {
                    loadOfficialStatus(true, CommonConstants.YNS_SIGN_REFRESH);
                } else {
                    loadStatus(true, ACTIONs.actionAlbumStatusRefresh);
                }
            }
        }, 500);
    }

    // 更新动态数据
    private void updateView(boolean isTop) {
        mRefreshlayout.setRefreshing(false);
        if (isTop) {
            if (isOfficialAlbum) {
                mAlbumStatusAdapter.addItemsFromTop(YNSingleton.getInstance().getStatusList());
            } else {
                mCardAlbumStatusAdapter.addItemsFromTop(YNSingleton.getInstance().getStatusList());
            }
            mRecyclerView.scrollToPosition(0);
        } else {
            if (isOfficialAlbum) {
                mAlbumStatusAdapter.addItemsFromBottom(YNSingleton.getInstance().getStatusList());
            } else {
                mCardAlbumStatusAdapter.addItemsFromBottom(YNSingleton.getInstance().getStatusList());
            }
            if (YNSingleton.getInstance().getStatusList().size() == 0) {
                isBottom = true;
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.TheEnd, null);
            } else {
                RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
            }
        }
        YNSingleton.getInstance().clearStatusList();
        if (refresh) {
            mCardAlbumStatusAdapter.notifyDataSetChanged();
            refresh = false;
        }
    }

    // 普通相册加载
    private void loadStatus(boolean isTop, String action) {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), AlbumContentService.class);
        mIntent.setAction(action);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mCardAlbumStatusAdapter.getIdByDirection(isTop));
        getActivity().startService(mIntent);
    }

    // 官方相册加载
    private void loadOfficialStatus(boolean isTop, String type) {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionOfficialAlbumStatus);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mAlbumStatusAdapter.getIdByDirection(isTop));
        mIntent.putExtra(ACTIONs.aNeedType, type);
        mIntent.putExtra(ACTIONs.aIsInAlbum, isFromHome ? 1 : YNSingleton.getInstance().getCurAlbum().getIsInAlbum());
        getActivity().startService(mIntent);
    }

    // 分析并执行动作
    BroadcastReceiver mStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
//                case ACTIONs.actionStatusUpdate:
//                    updateView(false);
//                    break;
                case ACTIONs.actionStatusUpdateRefresh:
                    updateView(true);
                    break;
                case ACTIONs.actionOfficialStatusUpdate:
                    boolean istop = intent.getBooleanExtra("isTop", false);
                    updateView(istop);
                    break;
                // 加入相册
                case ACTIONs.actionJoinState:
                    if (isOfficialAlbum) {
                        mAlbumStatusAdapter.setIsInAlbum(true);
                    } else {
                        mCardAlbumStatusAdapter.setIsInAlbum(true);
                    }
                    break;
                case ACTIONs.actionComment:
                    if (isOfficialAlbum) {
                        mAlbumStatusAdapter.SyncComment();
                    } else {
                        mCardAlbumStatusAdapter.SyncComment();
                    }
                    break;
                case ACTIONs.actionStatus:
                    boolean isAdd = intent.getExtras().getBoolean(ACTIONs.IsAdd);
                    int statusID = intent.getExtras().getInt(ACTIONs.StatusId);
                    doSyncStatus(isAdd, statusID);
                    break;
                case ACTIONs.actionSinglePhoto:
                    String PhotoUrl = intent.getStringExtra(ACTIONs.PhotoUrl);
                    for (int i = 0; i < groupStatusItems.size(); i++) {
                        if (PhotoUrl != null && PhotoUrl.equals(groupStatusItems.get(i).getUrl())) {
                            groupStatusItems.remove(i);
                            if (isOfficialAlbum) {
                                mAlbumStatusAdapter.notifyItemRemoved(i);
                            } else {
                                mCardAlbumStatusAdapter.notifyItemRemoved(i);
                            }
                            break;
                        }
                    }
                    break;
                case ACTIONs.actionStatusDleteUpdate:
                    if (isOfficialAlbum) {
                        loadOfficialStatus(true, CommonConstants.YNS_SIGN_REFRESH);
                    } else {
                        loadStatus(true, ACTIONs.actionAlbumStatusRefresh);
                    }
                    break;
                case ACTIONs.actionLookStatus:
                    if (intent != null) {
                        int eid = intent.getIntExtra("eid", 0);
                        lookStatus(eid);
                    }
                    break;
                case ACTIONs.modifyStatus:
                    groupStatusItems.clear();
                    refresh = true;
                    noticeServiceInit();
                    break;
            }
        }
    };

    // 同步动态
    private void doSyncStatus(boolean isAdd, int statusID) {
        if (isAdd) {
            if (statusID == YNSingleton.getInstance().getCurStatus().getEid()) {
                if (isOfficialAlbum) {
                    mAlbumStatusAdapter.addItemsFromTopOne(YNSingleton.getInstance().getCurStatus());
                } else {
                    mCardAlbumStatusAdapter.addItemsFromTopOne(YNSingleton.getInstance().getCurStatus());
                }
                mRecyclerView.scrollToPosition(0);
            }
        } else {
            if (isOfficialAlbum) {
                mAlbumStatusAdapter.removeOne(statusID);
            } else {
                mCardAlbumStatusAdapter.removeOne(statusID);
            }
        }
    }

    // 注册接收者
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionStatusUpdate);
        myIntentFilter.addAction(ACTIONs.actionStatusDleteUpdate);
        myIntentFilter.addAction(ACTIONs.actionStatusUpdateRefresh);
        myIntentFilter.addAction(ACTIONs.actionOfficialStatusUpdate);
        myIntentFilter.addAction(ACTIONs.actionJoinState);
        myIntentFilter.addAction(ACTIONs.actionComment);
        myIntentFilter.addAction(ACTIONs.actionStatus);
        myIntentFilter.addAction(ACTIONs.actionSinglePhoto);
        myIntentFilter.addAction(ACTIONs.actionLookStatus);
        myIntentFilter.addAction(ACTIONs.timeLineLead);
        myIntentFilter.addAction(ACTIONs.modifyStatus);
        getActivity().registerReceiver(mStatusBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载相册数据
    private void noticeServiceInit() {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), AlbumContentService.class);
        if (isOfficialAlbum) {
            mIntent.setAction(ACTIONs.actionOfficialAlbumStatus);
            mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
            mIntent.putExtra(ACTIONs.aIsInAlbum, isFromHome ? 1 : YNSingleton.getInstance().getCurAlbum().getIsInAlbum());
        } else {
            mIntent.setAction(ACTIONs.actionAlbumStatus);
        }
        mIntent.putExtra(ACTIONs.aLoadId, 0);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        getActivity().startService(mIntent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mStatusBroadcastReceiver);
    }

//    @Override
//    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
//        if (i == 0) {
//            mRefreshlayout.setEnabled(true);
//        } else {
//            mRefreshlayout.setEnabled(false);
//        }
//    }

    private void lookStatus(int eid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("eventid", String.valueOf(eid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynWatchStatus))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }
}
